#! /usr/bin/env python
# encoding=utf-8

from xml.sax import make_parser
from xml.sax.saxutils import XMLGenerator
import cgi
import os

if cgi.FieldStorage()['mode'].value == 'modify':
	id = cgi.FieldStorage()['id'].value
	content = cgi.FieldStorage()['content'].value
	
	class Handler(XMLGenerator):
		def __init__(self, file, id, content):
			self.id = id
			self.content = content
			self.flag1 = False
			self.flag2 = False
			XMLGenerator.__init__(self, file)
		
		def startElement(self, name, attrs):
			if name == 'partido' and attrs.getValue('id') == self.id:
				self.flag1 = True
			if self.flag1 and name == 'resultado':
				self.flag2 = True
			XMLGenerator.startElement(self, name, attrs)
		
		def characters(self, content):
			if self.flag1 and self.flag2:
				content = self.content
				self.flag1 = False
				self.flag2 = False
			XMLGenerator.characters(self, content)
		
	parser = make_parser()
	parser.setContentHandler(Handler(open('/tmp/db-temp.xml', 'w'), id, content))
	parser.parse('/tmp/db.xml')

	os.remove('/tmp/db.xml')
	os.rename('/tmp/db-temp.xml', '/tmp/db.xml')

	print 'Content-Type: text/plain'
	print
	print 'OK'
	
elif cgi.FieldStorage()['mode'].value == 'get':
	doc = open('/tmp/db.xml').read()
	print 'Content-Type: text/xml'
	print
	print doc